package top.malaoshi.netdisk.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.malaoshi.jdbc.Record;
import top.malaoshi.jdbc.RecordListUtil;
import top.malaoshi.netdisk.component.RecordListKeyHandler;
import top.malaoshi.netdisk.vo.JsonCodeMsg;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.netdisk.vo.NoteType;
import top.malaoshi.sprout.jdbc.DbTemplate;
import top.malaoshi.util.DateTime;
import top.malaoshi.util.id.SnowflakeIdWorker;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class NoteTypeSrvImpl {

    @Resource
    private DbTemplate jdbcTemplate;

    @Resource
    private RecordListKeyHandler recordListKeyHandler;
    /**
     *
     * @return
     * @throws Exception
     */
    public List<Map> query() throws Exception {

        String sql = "select nt_id,nt_name from t_note_type where nt_status = 1 order by create_time";
        List<Record> list = jdbcTemplate.query(sql );

        List<Map> retList = RecordListUtil.list(list, recordListKeyHandler);
        return retList;

    }

    /**
     * 保存
     * @param noteType
     * @throws Exception
     */
    public void save( NoteType noteType) throws Exception{
        Long id = SnowflakeIdWorker.getId();
        String now = DateTime.now();
        String sql = "insert into t_note_type (nt_id,nt_name,nt_status,create_time,modify_time) values (?,?,1,?,?)";
        jdbcTemplate.update(sql, id, noteType.getName(), now, now);
    }

    /**
     * 修改
     * @param noteType
     * @throws Exception
     */
    public void updateById(NoteType noteType) throws Exception{
        String now = DateTime.now();

        String sql = "update t_note_type set nt_name = ?,modify_time = ? where nt_id = ? ";
        jdbcTemplate.update(sql, noteType.getName(),now,noteType.getId());

    }

    /**
     * 删除到回收站
     * @param id
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult recycleById(String id) throws Exception{
        String countSQL = "select count(1) from t_note where t_id = ?";
        int count = jdbcTemplate.query(countSQL, id).get(0).getIntValue(0);
        if(count>0){
            return JsonResult.fail(JsonCodeMsg.OPERATE_FAIL.getCode(), "该文件夹下有笔记，不能删除！");
        }
        String sql = "update t_note_type set nt_status = 2 where nt_id = ? ";
        jdbcTemplate.update(sql,id);
        return JsonResult.success("删除成功！");
    }

    /**
     * 物理删除
     * @param id
     * @throws Exception
     */
    public void deleteById(String id) throws Exception{

        String sql = "delete from t_note_type where nt_id = ? ";
        jdbcTemplate.update(sql,id);

    }
}
